﻿import axios from "axios";
import router from "@/router";
import {ElMessageBox} from "element-plus";

axios.defaults.baseURL = 'http://localhost:5112'
let is401AlertShow = false

// axios拦截器分为两类，第一类叫做请求拦截器，第二类叫做响应拦截器
// 请求拦截器
axios.interceptors.request.use(
  config => {
    // 判断是否存在token值，如果存在则在请求前给header中加上token
    console.log(localStorage['token'])
    if (localStorage['token']) {
      if (config?.headers != null)
        config.headers.authorization = 'Bearer ' + localStorage['token'] // 请求头加上token
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)
// 响应拦截器
axios.interceptors.response.use(
  response => response,
  error => {
    switch (error.response.status) {
      case 401: {
        router.push('/')
        if (!is401AlertShow) {
          is401AlertShow = true
          ElMessageBox.alert('无权限',
            {
              callback: () => {
                is401AlertShow = false
              }
            })
        }
        break
      }
    }
  }
)
export default axios
